import React, {
  FC,
  ReactElement,
  Fragment,
  useRef,
  useState,
} from 'react';
import { Form, Button, Image, Toast, Popover } from '@douyinfe/semi-ui';
import type { FormApi } from '@douyinfe/semi-ui/lib/es/form';
import { IconPlus, IconMinus, IconEyeOpened } from '@douyinfe/semi-icons';
import { useFieldList, useCityList } from '@/store';
import type { FieldsGoodsItem } from '../types';

import './Detail.scss';

interface IProps {
  id?: string | number;
  currentRow?: Partial<FieldsGoodsItem>;
  handleCloseModal: () => void;
  handleAddSubmit: (formValue: Partial<FieldsGoodsItem>) => void | Promise<void>;
  handleEditSubmit: (id: string | number, formValue: Partial<FieldsGoodsItem>) => void | Promise<void>;
}

const {
  Input,
  Select,
  Label,
  InputNumber,
  TextArea,
  Rating,
} = Form;

const FieldsGoodsOperate: FC<IProps> = (props): ReactElement => {
  const { id, currentRow, handleCloseModal, handleAddSubmit, handleEditSubmit } = props;

  const fieldList = useFieldList();
  const cityList = useCityList();

  const formApiRef = useRef<FormApi<Partial<FieldsGoodsItem>>>(null);
  const [previewImg, setPreviewImg] = useState<HTMLInputElement | null>(null);

  const [banners, setBanners] = useState<string[]>(currentRow?.banners || []);
  const [formLoading, setFormLoading] = useState(false);

  async function handleSubmit() {
    try {
      if (!formApiRef.current) return;
      const formApi = formApiRef.current;

      // 1. 校验是否合法
      await formApi.validate();

      // 2. 收集数据
      setFormLoading(true);
      const formValue = formApi.getValues();

      // 3. 提交数据
      if (id) {
        await handleEditSubmit(id, {
          ...formValue,
          banners,
        });
      } else {
        await handleAddSubmit({
          ...formValue,
          banners,
        });
      }
    } catch (e) {
      Toast.error(e instanceof Error ? e.message : '提交失败');
    }
    setFormLoading(false);
  }

  return (
    <div className="fields-goods-list-detail">
      <Form
        layout="vertical"
        initValues={id ? (currentRow ?? {}) : undefined}
        getFormApi={formApi => formApiRef.current = formApi}
        labelPosition="left"
        labelAlign="right"
        labelWidth="150px"
      >
        <Input
          label="名称"
          field="name"
          initValue={currentRow?.name ?? ''}
          rules={[
            { required: true, message: '请填写名称' },
          ]}
          placeholder="请填写名称"
          style={{ width: 320 }}
        />
        <Select
          label="类型"
          field="field"
          rules={[
            { required: true, message: '请选择类型' },
          ]}
          style={{ width: 320 }}
          placeholder="请选择类型"
          optionList={fieldList.map(item => ({
            label: item.name,
            value: item.key,
          }))}
        />
        <Select
          label="所在城市"
          field="cityName"
          rules={[
            { required: true, message: '请选择所在城市' },
          ]}
          style={{ width: 320 }}
          placeholder="请选择所在城市"
          filter
          optionList={cityList.map(item => ({
            label: item.name,
            value: item.key,
          }))}
        />
        <Input
          label={<span>封面图片</span>}
          ref={(ref: HTMLInputElement) => setPreviewImg(ref)}
          field="img"
          rules={[
            { required: true, message: '请填写封面图片' },
          ]}
          suffix={(
            <Popover
              trigger="click"
              content={<Image src={previewImg?.value} width={300} height={240} />}
            >
              <Button
                icon={<IconEyeOpened />}
                type="tertiary"
                style={{ position: 'relative', left: 30 }}
              />
            </Popover>
          )}
          style={{ width: 320 }}
          placeholder="请填写封面图片"
        />
        <div>
          <Label style={{ marginLeft: 66 }}>
            封面图片组
            <Button
              icon={<IconPlus />}
              type="tertiary"
              style={{ marginLeft: 10 }}
              disabled={banners.length >= 5}
              onClick={() => setBanners(b => [...b, ''])}
            />
          </Label>
          {banners.map((item, index) => {
            return (
              <Fragment key={index}>
                <Input
                  placeholder={`封面图片-${index + 1}`}
                  field={`banners[${index}]`}
                  defaultValue={item}
                  style={{ width: 360 }}
                  suffix={
                    <Button
                      icon={<IconMinus />}
                      type="tertiary"
                      style={{ marginLeft: 20, position: 'relative', left: '44px' }}
                      onClick={() => {
                        setBanners(banners => banners.filter((_, i) => i !== index));
                      }}
                    />
                  }
                  onBlur={e => setBanners(banners => {
                    banners[index] = e.target.value;
                    return banners;
                  })}
                />
                {item.length > 0 && (
                  <Image
                    src={item}
                    alt={`封面图片-${index + 1}`}
                    width={320}
                    height={100}
                    style={{ marginLeft: 150 }}
                  />
                )}
              </Fragment>
            )
          })}
          <Input
            label="最低价格"
            field="defaultPrice"
            rules={[
              { required: true, message: '请填写最低价格' },
            ]}
            placeholder="请填写最低价格"
            style={{ width: 320 }}
          />
          <Input
            label="平均价格"
            field="price"
            rules={[
              { required: true, message: '请填写平均价格' },
            ]}
            placeholder="请填写平均价格"
            style={{ width: 320 }}
          />
          <Input
            label="地址"
            field="address"
            placeholder="请填写地址"
            style={{ width: 320 }}
          />
          <Input
            label="推荐内容"
            field="recom"
            placeholder="请填写推荐内容"
            style={{ width: 320 }}
          />
          <Input
            label="关键词"
            field="keywords"
            placeholder="请填写关键词 (多个用英文逗号分隔)"
            style={{ width: 320 }}
          />
          <Rating
            label="星评"
            field="star"
            initValue={currentRow?.star ?? 3}
          />
          <InputNumber
            label="分数"
            field="score"
            min={0}
            max={10}
            style={{ width: 320 }}
            initValue={currentRow?.score ?? 6}
          />
          <TextArea
            label="描述"
            field="description"
            placeholder="请填写描述"
            rows={3}
            maxLength={200}
            style={{ width: 320 }}
            showCounter
          />
        </div>
      </Form>
      <footer className="btn-group">
        <Button onClick={handleCloseModal}>取消</Button>
        <Button
          loading={formLoading}
          type="primary"
          theme="solid"
          onClick={handleSubmit}
        >
          提交
        </Button>
      </footer>
    </div>
  )
}

export default FieldsGoodsOperate;
